
export default class AliBCZBUtils {
    private static instance: AliBCZBUtils;

    public static getInstance() {
        if (!this.instance) {
            this.instance = new AliBCZBUtils();
        }
        return this.instance;
    }

    private mAliBCzb: ApicloudModules['aliBCzb'];

    private constructor() {
        this.mAliBCzb = api.require('aliBCzb')
        if (!this.mAliBCzb) {
            throw new Error('aliBCzb 模块没引入')
        }
    }
    /**
     * 初始化,全局调用一次
     */
    public init() {
        return new Promise<{ status: boolean, msg: string }>(res => {
            this.mAliBCzb.asyncInit({
                params: { open4GDownload: true }
            }, (ret, err) => {
                if (ret && ret.status) {
                    res({
                        status: true,
                        msg: '初始成功'
                    });
                } else {
                    res({
                        status: false,
                        msg: err ? err.message : '初始化失败'
                    });
                }
            })
        });
    }

    public registerImage() {
        this.mAliBCzb.registerImage()
    }

    /**
     * 注册分享点击事件
     */
    public registerNavigateUrl(cb: Function) {
        this.mAliBCzb.registerNavigateUrl({
            hook: true
        }, (ret) => {
            cb(ret.url)
        });
    }
    /**
     * 注册点击事件仅Andrid
     */
    public registerEventListener() {
        return new Promise<any>((res) => {
            this.mAliBCzb.registerEventListener((ret) => {
                res(ret)
            });
        })
    }
    /**
     * 获取用户信息
     */
    public getUserInfo() {
        return new Promise<UserInfo>((res) => {
            this.mAliBCzb.getUserInfo((ret, err) => {
                if (ret && ret.status) {
                    res({
                        ...ret,
                        msg: '获取成功'
                    });
                } else {
                    res(Object.assign({
                        status: false,
                        msg: err ? err.message : '获取失败'
                    }));
                }
            });
        });
    }
    /**
     * 显示淘宝登录
     */
    public showLogin() {
        return new Promise<UserInfo>((res) => {
            this.mAliBCzb.showLogin((ret, err) => {
                if (ret && ret.status) {
                    res({
                        ...ret,
                        msg: '登录成功'
                    });
                } else {
                    res(Object.assign({
                        status: false,
                        msg: err ? err.message : '未登录'
                    }));
                }
            });
        });

    }
    /**
     * 打开链接
     * @param params 
     */
    public openByUrl(params: {
        url: string;
        openType?: 'auto' | 'native';
        linkKey?: 'taobao' | 'tmall',
        pid?: string;
        relationId?: string;
        materialSourceUrl?: string;
        tk_extParams?: { [key: string]: any };
        backUrl?: string;
        degradeUrl?: string;
        failModeType?: 'h5' | 'none' | 'download';
        trackParams?: { [key: string]: any };
    }) {
        return new Promise<{ status: boolean, msg: string }>(res => {
            this.mAliBCzb.openByUrl(params, (ret, err) => {
                if (ret && ret.status) {
                    res({
                        ...ret,
                        msg: '打开成功'
                    });
                } else {
                    res(Object.assign({
                        status: false,
                        msg: err ? err.message : '打开失败'
                    }));
                }
            });
        });
    }
    /**
     * 打开百川套件
     * @param params 
     */
    public openByCode(params: {
        code?: string,
        id?: string,
        shopId?: string,
        sellerId?: string,
        biz_extParams?: {
            id?: string;
            couponActivityId?: string;
            vegasCode?: string;
            pageType?: string;
            flRate?: string;
            dlRate?: string;
            maxDlRate?: string;
            isvUserId?: string;
        },
        openType?: 'auto' | 'native';
        linkKey?: 'taobao' | 'tmall',
        pid: string;
        relationId: string;
        materialSourceUrl?: string;
        tk_extParams?: { [key: string]: any };
        backUrl?: string;
        degradeUrl?: string;
        failModeType?: 'h5' | 'none' | 'download';
        trackParams?: { [key: string]: any };
    }) {
        return new Promise<{ status: boolean, msg: string }>(res => {
            this.mAliBCzb.openByCode(params, (ret, err) => {
                if (ret && ret.status) {
                    res({
                        ...ret,
                        msg: '打开成功'
                    });
                } else {
                    res(Object.assign({
                        status: false,
                        msg: err ? err.message : '打开失败'
                    }));
                }
            });
        });
    }

    /**
     * 打开授权
     * @param clientId 等同于appkey，创建应用时获得。
     * @param redirectUri 回调地址
     * @param state 自定义数据
     */
    public async openAuthorize(params: {
        clientId: string,
        redirectUri: string,
        state: string
    }): Promise<{ status: boolean, msg: string }> {
        let userInfo = await this.getUserInfo();
        if (!userInfo.status || !userInfo.isLogin) {
            userInfo = await this.showLogin();
            if (!userInfo.isLogin || !userInfo.status) {

                return {
                    status: false,
                    msg: '取消授权'
                }
            }
        }
        return this.openByUrl({
            url: `https://oauth.m.taobao.com/authorize?response_type=code&client_id=${params.clientId}&redirect_uri=${params.redirectUri}&state=${params.state}`
        });
    }
}


interface UserInfo {
    status: boolean,  			//是否授权登录成功
    isLogin: boolean,    		//是否授权登录成功
    nick: string,              //昵称
    avatarUrl: string,         //头像地址
    openId: string,            //用户标识
    openSid: string,            //用户标识
    userid: string,			//仅android有此返回值
    topAccessToken: string        //仅iOS有此返回值
    topAuthCode: string		//仅iOS有此返回值
    msg: string
}